# coding: utf-8
from __future__ import unicode_literals
import os
import sys
import pprint
import ldap

SERVER_URI = "ldap://10.33.64.30:389"
BASE_DN = "dc=VDIN,dc=local"
BIND_DN = "cn=manti,ou=vCAC,dc=VDIN,dc=local"
BIND_PASSWORD = "123456"
SEARCH_FILTER = "(|(sAMAccountName=%(user)s)(mail=%(user)s))"

ldap.set_option(ldap.OPT_REFERRALS, 0)
con = ldap.initialize(SERVER_URI)


def connection(user_dn, password):
    base_con = con
    base_con.simple_bind_s(user_dn, password)
    return base_con


def authentication(username, password):
    filterstr = SEARCH_FILTER % {"user": username}
    try:
        results = connection(BIND_DN, BIND_PASSWORD).search_s(BASE_DN, ldap.SCOPE_SUBTREE, filterstr)
    except ldap.LDAPError as e:
        print("search_s('{}', {}, '{}') raised {}".format(
                BASE_DN, ldap.SCOPE_SUBTREE, filterstr, pprint.pformat(e)))
        raise e
    user_dn = results[0][0]

    connection(user_dn, password)
    print("Authenticate Success")

if __name__ == "__main__":
    username = os.environ.get("username")
    password = os.environ.get("password")
    if username is None or password is None:
        sys.exit(1)
    sys.exit(authentication(username, password))



    
    